package com.yunshan.system.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author admin001
 */
@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String SECRET_KEY;
    @Value("${jwt.accessExpiration}")
    private long ACCESS_EXPIRATION;

    // 生成 Access Token（包含 openid 和 userId、 unionId）
    public String generateAccessToken(Long userId, String openid, String unionId) {
        return Jwts.builder()
                .claim("userId",String.valueOf(userId))
                .claim("openid", openid)
                .claim("unionId", unionId)
                .setExpiration(new Date(System.currentTimeMillis() + ACCESS_EXPIRATION * 1000))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 生成 Refresh Token（仅关联 openid）
    public String generateRefreshToken(String openid) {
        return Jwts.builder()
                .setSubject(openid)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 解析 Token
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }
}
